package com.icesoft.core.common.util;

import org.springframework.util.StreamUtils;

import java.io.*;

public class FileUtil {

    public static byte[] readByteArray(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        StreamUtils.copy(fis, byteArrayOutputStream);
        fis.close();
        byteArrayOutputStream.close();
        return byteArrayOutputStream.toByteArray();
    }

    public static void writeByteToFile(File file, byte[] bytes) throws IOException {
        writeByteToFile(file, bytes, false);
    }

    public static void writeByteToFile(File file, byte[] bytes, boolean append) throws IOException {
        OutputStream out = openOutputStream(file, append);
        out.write(bytes);
        out.flush();
        out.close();
    }

    public static FileOutputStream openOutputStream(File file) throws IOException {
        return openOutputStream(file, false);
    }

    public static FileOutputStream openOutputStream(File file, boolean append) throws IOException {
        checkFileCanWrite(file);
        return new FileOutputStream(file, append);
    }

    /**
     * 校验文件是否有效，并生成目录
     */
    public static void checkFileCanWrite(File file) throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File '" + file + "' exists but is a directory");
            }
            if (file.canWrite() == false) {
                throw new IOException("File '" + file + "' cannot be written to");
            }
        } else {
            File parent = file.getParentFile();
            if (parent != null) {
                if (!parent.mkdirs() && !parent.isDirectory()) {
                    throw new IOException("Directory '" + parent + "' could not be created");
                }
            }

        }
    }

}